<?php
namespace iBrand\Shop\Server\Http\Controllers;

use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Models\Shop;
use iBrand\Shop\Core\Repositories\ClerkRepositoryEloquent;
use iBrand\Server\Exception\UserExistsException;
use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use League\OAuth2\Server\Exception\OAuthServerException;
use RuntimeException;
use Validator;
use Hash;
use Image;
use iBrand\Shop\Core\Repositories\ShopOrderRepository;
use iBrand\Shop\Core\Repositories\UserShopRepository;
use iBrand\Shop\Core\Repositories\OrderRepository;
use iBrand\Shop\Server\Transformers\ShopOrderTransformer;

class ClerkController extends Controller
{
    private $clerkRepository;
    protected $shopOrderRepository;
    protected $userShopRepository;
    protected $orderRepository;

    public function __construct(
        ClerkRepositoryEloquent $clerkRepository,
        ShopOrderRepository $shopOrderRepository,
        UserShopRepository $userShopRepository,
        OrderRepository $OrderRepository
    )
    {
        $this->clerkRepository = $clerkRepository;
        $this->shopOrderRepository = $shopOrderRepository;
        $this->userShopRepository = $userShopRepository;
        $this->orderRepository = $OrderRepository;
    }

    public function index()
    {
        $clerk = auth('clerk')->user();

        if ($clerk->is_clerk_owner == 1) {
            if ($res = $this->clerkRepository->getClerkByShopId($clerk->shop_id)) {
                return $this->api(collect($res)->sortByDesc('is_clerk_owner')->values()->all(), true, 200, '');
            }
        }
        return $this->api([], false, 405, '获取失败');
    }

    public function edit($id)
    {
        $clerk = auth('clerk')->user();
        if ($clerk->is_clerk_owner == 1) {
            $res = $this->clerkRepository->find($id);
            if ($res && $res->shop_id == $clerk->shop_id) {
                if ($res->avatar) $res->avatar = url($res->avatar);
                return $this->api($res, true, 200, '');
            }
        }
        return $this->api([], false, 405, '编辑失败');
    }

    public function update($id)
    {
        $clerk = auth('clerk')->user();
        if ($clerk->is_clerk_owner == 1) {
            $res = $this->clerkRepository->find($id);
            if ($res && $res->shop_id == $clerk->shop_id) {
                $input = request()->only('name', 'mobile', 'status', 'nickname');
                foreach ($input as $k => $item) {
                    if ($k == 'status' && $item == 0 && $id == $clerk->id) {
                        return $this->api([], false, 405, '');
                    }
                    if ($item === null) {
                        unset($input[$k]);
                    }
                }
                if ($this->clerkRepository->update($input, $id)) {
                    return $this->api([], true, 200, '保存成功');
                };
            }

        }
        return $this->api([], false, 405, '保存失败');
    }


//    修改昵称
    public function updateNickname(Request $request)
    {
        $clerk = auth('clerk')->user();
        $validator = Validator::make($request->all(), [
            'nickname' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => 'false',
                'message' => $validator->errors(),
            ]);
        };
        if (Clerk::find($clerk->id)->update(['nickname' => $request->input('nickname')])) {
            return $this->api([], true, 200, '保存成功');
        }
        return $this->api([], false, 405, '保存失败');
    }


//    修改头像
    public function uploadAvatar(Request $request)
    {

        $clerk = auth('clerk')->user();

        //TODO: 需要验证是否传入avatar_file 参数
        $file = $request->file('avatar_file');
        $Orientation = $request->input('Orientation');

        $destinationPath = storage_path('app/public/uploads');
        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0777, true);
        }

        $extension = $file->getClientOriginalExtension();
        $filename = $this->generaterandomstring() . '.' . $extension;

        $image = $file->move($destinationPath, $filename);

        $img = Image::make($image);

        switch ($Orientation) {
            case 6://需要顺时针（向左）90度旋转
                $img->rotate(-90);
                break;
            case 8://需要逆时针（向右）90度旋转
                $img->rotate(90);
                break;
            case 3://需要180度旋转
                $img->rotate(180);
                break;
        }

        $img->resize(320, null, function ($constraint) {
            $constraint->aspectRatio();
        })->crop(320, 320, 0, 0)->save();

        $this->clerkRepository->update(['avatar' => '/storage/uploads/' . $filename], $clerk->id);

//        if (request('action') == 'save') {
//            $this->clerkRepository->update(['avatar'=>'/storage/uploads/' . $filename],$clerk->id);
//        }

        return $this->api(['url' => url('/storage/uploads/' . $filename)]);
    }


    private function generaterandomstring($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function me()
    {
        $clerk = auth('clerk')->user();
        /*if ($clerk->avatar) $clerk->avatar = url($clerk->avatar);*/
        return $this->api($clerk, true, 200, '');
    }

    public function bonus()
    {

        $clerk = auth('clerk')->user();

        $bonus_all = $this->shopOrderRepository->getBonusByClerkID($clerk->id);

        $bonus_today = $this->shopOrderRepository->getBonusTodayByClerkID($clerk->id);

        $list = $this->shopOrderRepository->getBonusOrderList($clerk->id);

        return $this->response()->paginator($list, new ShopOrderTransformer())->setMeta(['bonus_today' => $bonus_today, 'bonus_all' => $bonus_all,]);

    }


    /**
     * 数据统计
     * @return \Dingo\Api\Http\Response
     */
    public function count()
    {
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;
        $user_today = $this->userShopRepository->getUserCountTodayByClerkID($clerk->id);
        $user_7_day = $this->userShopRepository->getUserCountDayByClerkID($clerk->id, -7);
        $user_30_day = $this->userShopRepository->getUserCountDayByClerkID($clerk->id, -30);
        $order_today = $this->shopOrderRepository->getOrderCountTodayByClerkID($clerk->id);
        $order_7_day = $this->shopOrderRepository->getOrderCountDayByClerkID($clerk->id, -7);
        $order_30_day = $this->shopOrderRepository->getOrderCountDayByClerkID($clerk->id, -30);
        $total_today = $this->orderRepository->getOrderTotalCountTodayByClerkID($clerk->id, $shop_id);
        $total_7_day = $this->orderRepository->getOrderTotalCountDayByClerkID($clerk->id, -7, $shop_id);
        $total_30_day = $this->orderRepository->getOrderTotalCountDayByClerkID($clerk->id, -30, $shop_id);
        return $this->api(
            [

                'user_today' => $user_today,
                'user_7_day' => $user_7_day,
                'user_30_day' => $user_30_day,

                'order_today' => $order_today,
                'order_7_day' => $order_7_day,
                'order_30_day' => $order_7_day,

                'total_today' => $total_today,
                'total_7_day' => $total_7_day,
                'total_30_day' => $total_7_day
            ], true, 200, '');
    }


}